require 'socket'

module CloudHash
  class Server
    def initialize(port)
      @server = TCPServer.new(port)
      puts "Listening on port #{@server.local_address.ip_port}"
      @storage = {}
    end

    def start
      #accept 循环
      Socket.accept_loop(@server) do |conn|
        puts "accept from #{conn.remote_address.ip_port}"
        handle(conn)
        conn.close
      end
    end

    def handle(conn)
      #从链接中读取数据
      request = conn.read
      puts "request #{request}"
      #将结果回写
      conn.write(process(request))
    end

    # 进行处理
    # set key value
    # get key
    def process(request)
      command,key,value = request.split
      case command.upcase
        when 'GET'
          @storage[key]
        when 'SET'
          @storage[key] = value
      end
    end
  end
end

server = CloudHash::Server.new(4481)
server.start